import axios from 'axios'
// import Toast from 'muse-ui-toast'
import Vue from 'vue'
import store from '../store'
import md5 from 'js-md5'
import { parseTime } from '@/utils'
import { Toast } from 'vant'
Vue.use(Toast)
// import resConfig from './config'

// import { getToken } from '@/utils/auth'
// import qs from 'qs'
// 创建axios实例
const service = axios.create({
  baseURL: '/api', //  http://47.98.56.1 process.env.BASE_API, // api的 base_url
  timeout: 15000 // 请求超时时间,
  // headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = 'Bearer ' + store.getters.token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // console.log('config', config)
  if (config.params) {
    config.params = Object.assign({}, config.params)
    config.params.timestamp = parseTime(new Date())
    config.params.sign = getSign(config.params)
  }
  if (config.data) {
    config.data = Object.assign({}, config.data)
    config.data.timestamp = parseTime(new Date())
    config.data.sign = getSign(config.data)
    // config.data = qs.stringify(config.data)
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// response 拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
    const res = response.data
    if (res.code === 201) {
      store.dispatch('FedLogOut').then(() => {
        const href = location.origin + location.pathname + '#/'
        location.href = href
      })
      return response.data
    }
    if (res.code !== 200 && res.msg) {
      if (res.msg !== 'FAIL') {
        Toast(res.msg)
        setTimeout(() => {
          Toast.clear()
        }, 5000)
      } else {
        Toast('服务器出错')
      }
    }
    return response.data
    //   // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     Toast.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
    //       confirmButtonText: '重新登录',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('FedLogOut').then(() => {
    //         location.reload()// 为了重新实例化vue-router对象 避免bug
    //       })
    //     })
    //   }
    //   return Promise.reject('error')
    // } else {
    //   return response.data
    // }
  },
  error => {
    if (error.response) {
      console.log('error.response.message', error.response.data.message)
      if (error.response.data && error.response.data.msg && error.response.data.msg !== 'FAIL') {
        Toast(error.response.data.msg)
      }
      setTimeout(() => {
        Toast.clear()
      }, 2000)
      if (error.response.data.message === 'No user found with username') {
        store.dispatch('FedLogOut').then(() => {
          const href = location.origin + location.pathname + '#/login?back=1'
          location.href = href
        })
      }
      // No user found with username
      if (error.response.code === 403) {
        store.dispatch('FedLogOut').then(() => {
          // location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      }
      if (error.response.status === 403) {
        store.dispatch('FedLogOut').then(() => {
          // location.reload()// 为了重新实例化vue-router对象 避免bug
        })
      }
    }
    return Promise.reject(error)
  }
)
export function getSign(obj) {
  const arr = Object.keys(obj)
  arr.sort()
  let stringA = ''
  arr.forEach(function(item, index) {
    if (!obj[item]) {
      return
    }
    if (Array.prototype.isPrototypeOf(obj[item]) && obj[item].length === 0) {
      return
    }
    if (Object.prototype.isPrototypeOf(obj[item]) && Object.keys(obj[item]).length === 0) {
      return
    }
    stringA += item + '=' + obj[item]
    if (index !== arr.length - 1) {
      stringA += '&'
    }
  })
  var url = stringA + `&key=njcRD9o9nEUHpXJA`
  // console.log('url', url)
  return md5(url).toLocaleUpperCase()
}
export default service
